package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author atguigu-mqx
 * @ClassName TrackStrategyImpl
 * @description: TODO
 * @date 2024年10月14日
 * @version: 1.0
 */
@Service("1002")
public class TrackStrategyImpl implements ItemTypeStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //  购买声音 user_paid_track
        //  select * from user_paid_track where user_id = ? and track_id in();
        LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPaidTrack::getUserId, userPaidRecordVo.getUserId()).in(UserPaidTrack::getTrackId, userPaidRecordVo.getItemIdList());
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(wrapper);
        if (userPaidTrackList.size() > 0) return;
        //  根据声音Id获取到声音对象；
        //  userPaidRecordVo.getItemIdList().get(0) 获取第一个声音Id
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0));
        Assert.notNull(trackInfoResult.getData(), "声音信息不存在！");
        TrackInfo trackInfo = trackInfoResult.getData();
        Assert.notNull(trackInfo, "声音所属专辑不存在！");
        //  否则就添加:
        for (Long trackId : userPaidRecordVo.getItemIdList()) {
            //  创建用户购买声音对象
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setTrackId(trackId);
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            //  保存购买声音记录.
            userPaidTrackMapper.insert(userPaidTrack);
        }
    }
}
